//    Copyright (C) Kherty.  All rights reserved.
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Reflection;
using OpenLS.Drawing;

namespace OpenLS.Chart.UI
{
    public class ShapePropertiesObserver
    {}
    public class ShapePropertiesObserver<TSeries>: ShapePropertiesObserver, INotifyPropertyChanged where TSeries: Series
    {
        public ShapePropertiesObserver(ObservableCollection<TSeries> series)
        {
            this.series = series;
            series.CollectionChanged += Series_CollectionChanged;
            SetEvents();
        }

        private void SetEvents()
        {
            foreach (TSeries s in series)
            {
                s.PropertyChanged += s_PropertyChanged;
                if (s.ShapeProperties != null)
                    s.ShapeProperties.PropertyChanged += p_PropertyChanged;
            }
        }

        private readonly ObservableCollection<TSeries> series;

        void Series_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            SetEvents();
        }

        void s_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "ShapeProperties")
            {
                ShapeProperties p = ((BarSeries) sender).ShapeProperties;
                p.PropertyChanged += p_PropertyChanged;
            }
            if (e.PropertyName == "Shape")
                Pulse();
        }

        private void Pulse()
        {
            Generation++;
        }

        void p_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "FillProperties")
                Pulse();
        }
        private int generation;
        public int Generation
        {
            get { return generation; }
            set { generation = value;
                notifyPropertyChanged("Generation"); }
        }

        private void notifyPropertyChanged(string propertyName)
        {
            Contract.Requires(GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null); var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }
}
